package com.it.config;

import cn.hutool.json.JSONUtil;
import com.it.utisl.JwtUtils;
import com.it.vo.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 在认证成功时生成JWT，并将其设置到响应头中，然后返回一个成功的JSON响应
 *
 * @author: Coke
 * @DateTime: 2023/11/19/19:40
 **/
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    
    @Autowired
    private JwtUtils jwtUtils;
    
    @Override
    // 处理认证成功的逻辑
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 设置响应的内容类型为JSON，使用UTF-8字符集
        response.setContentType("application/json;charset=UTF-8");
        
        // 获取响应输出流
        ServletOutputStream outputStream = response.getOutputStream();
        
        // 生成JWT并设置到响应头
        String jwt = jwtUtils.generateToken(authentication.getName());
        response.setHeader(jwtUtils.getHeader(), jwt);
        
        // 构建成功响应
        Response<?> ok = Response.ok();
        
        // 将成功响应转换为JSON字符串，并写入输出流中
        outputStream.write(JSONUtil.toJsonStr(ok).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
